#include "ivbuffer_dx9.h"
#include "log.h"
#include "render_dx9.h"

vbuffer_dx9::vbuffer_dx9(IDirect3DDevice9* _device,u32 _size,buffer_usage _usage,u32 _format,u32 _block_size)
{
	m_format = _format;
	m_size = _size;
	m_block_size = _block_size;
	m_d3dvbuffer = 0;

	u32 d3d_usage = D3DUSAGE_WRITEONLY;
	if(_usage==usage_dynamic)
		d3d_usage |= D3DUSAGE_DYNAMIC;

	D3DCHECK(_device->CreateVertexBuffer(m_size,d3d_usage,m_format,D3DPOOL_DEFAULT,&m_d3dvbuffer,NULL));
}

vbuffer_dx9::~vbuffer_dx9()
{
	if(m_d3dvbuffer)
		m_d3dvbuffer->Release();
}

void* vbuffer_dx9::lock(buffer_lock _lock)
{
	u32 mode = 0;
	switch(_lock)
	{
		case lock_read:
			mode = D3DLOCK_READONLY;
			break;
		case lock_write:
		case lock_rewrite:
			mode = 0;
			break;
	}

	void *pData = 0;
	m_d3dvbuffer->Lock(0,0,&pData,mode);

	return pData;
}

void vbuffer_dx9::unlock()
{
	m_d3dvbuffer->Unlock();
}

ibuffer_dx9::ibuffer_dx9(IDirect3DDevice9* _device,u32 _size,buffer_usage _usage)
{
	m_d3dibuffer = 0;
	m_d3ddevice = _device;
	m_size = _size;

	u32 d3d_usage = D3DUSAGE_WRITEONLY;
	if(_usage==usage_dynamic)
		d3d_usage |= D3DUSAGE_DYNAMIC;

	D3DCHECK(m_d3ddevice->CreateIndexBuffer(m_size,d3d_usage,D3DFMT_INDEX16,D3DPOOL_DEFAULT,&m_d3dibuffer,NULL));

}

ibuffer_dx9::~ibuffer_dx9()
{
	if(m_d3dibuffer)
		m_d3dibuffer->Release();
}

void* ibuffer_dx9::lock(buffer_lock _lock)
{
	u32 mode = 0;
	switch(_lock)
	{
	case lock_read:
		mode = D3DLOCK_READONLY;
		break;
	case lock_write:
	case lock_rewrite:
		mode = 0;
		break;
	}

	void *pData = 0;
	m_d3dibuffer->Lock(0,0,&pData,mode);

	return pData;
}

void ibuffer_dx9::unlock()
{
	m_d3dibuffer->Unlock();
}